package cn.uyunsky.platform.taglib;

import cn.uyunsky.platform.BeanFactoryUtil;
import cn.uyunsky.platform.config.ConfigFactory;
import cn.uyunsky.platform.config.bean.combobox.ComboVO;
import cn.uyunsky.platform.config.bean.combobox.Entry;
import cn.uyunsky.platform.config.reader.ComboxReader;
import cn.uyunsky.platform.util.PL;

import javax.servlet.jsp.JspWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ComboxInputTag extends BaseInputTag {

    private static final long serialVersionUID = 1L;
    private static String STYLE_CLASS = "uyunsky_combox";

    private String combox;
    private String listHeight;

    public String getCombox() {
        return combox;
    }

    public void setCombox(String combox) {
        this.combox = combox;
    }

    public void setListHeight(String listHeight) {
        this.listHeight = listHeight;
    }


    public ComboxInputTag() {
    }

    protected String prepareOtherClass() {
        return STYLE_CLASS;
    }

    protected void prepareOtherAttributes(StringBuffer results) {
        prepareAttribute(results, "type", "text");
        prepareAttribute(results, "combox", combox);
        prepareAttribute(results, "listHeight", listHeight);
    }

    public String outputAfter() {
        Object hasData = pageContext.getAttribute(combox);
        StringBuffer outstr = new StringBuffer("");
        if (hasData == null) {
            ConfigFactory configFactory = (ConfigFactory) BeanFactoryUtil.getBean("configFactory");
            ComboxReader comboreader = configFactory.getReader(ComboxReader.class);
            List<Entry> entrys = comboreader.getEntrys(combox);
            if (entrys == null) entrys = new ArrayList();

            List<ComboVO> list = new ArrayList<ComboVO>();
            for (Entry entry : entrys) {
                ComboVO vo = new ComboVO();
                vo.setValue(entry.getKey());
                vo.setText(entry.getValue());
                list.add(vo);
            }
            outstr.append("<div id='" + combox + "_combox' class='comboxdata' style='display: none;'>");
            outstr.append(PL.JSON.toJSON(list));
            outstr.append("</div>");


            pageContext.setAttribute(combox, "");
        }
        return outstr.toString();
    }
}
